package gui5e;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.WatchEvent.Kind;
import java.util.Observable;
import java.util.Observer;

public class WatchFS extends Observable implements Runnable{
	private File folder;
	public File[] files;
	private volatile boolean isStopped = false;
	
	public WatchFS(Observer obs_, File folder_){
		this.folder=folder_;
		files =  folder_.listFiles();
		this.addObserver(obs_); 
	}
	
	public void run(){
		try {
			  //create the watchService
			  final WatchService watchService = FileSystems.getDefault().newWatchService();
			  //register the directory with the watchService
			  //for create, modify and delete events
			  final Path path = Paths.get(folder.getPath());
			  path.register(watchService,
			            StandardWatchEventKinds.ENTRY_CREATE,
			            StandardWatchEventKinds.ENTRY_MODIFY,
			            StandardWatchEventKinds.ENTRY_DELETE);
	
			  while(!isStopped){	  
			    //remove the next watch key
			    final WatchKey key = watchService.take();
			 
			    //get list of events for the watch key
			    for (WatchEvent<?> watchEvent : key.pollEvents()) {
			 
			      //get the filename for the event
			  //	NOT NEEDED YET  	
			      final WatchEvent<Path> ev = (WatchEvent<Path>)watchEvent;
			      final Path filename = ev.context();
			 
			      //get the kind of event (create, modify, delete)
			      final Kind<?> kind = watchEvent.kind();
			 
			      if(kind ==  StandardWatchEventKinds.ENTRY_MODIFY || kind == StandardWatchEventKinds.ENTRY_DELETE) {
						//System.out.println("something happend @ "+folder);
						files =  folder.listFiles();
						//call(folder.getName());
						//call(kind.name()+"?"+folder.getName());
						//System.out.println(kind.name()+"?"+folder.getAbsolutePath()+"?"+folder.getName()+"?"+filename.toString());
						call(kind.name()+"?"+folder.getAbsolutePath()+"?"+folder.getName()+"?"+filename.toString());
			      }
			    	  
			      //print it out
			    }
			 
			    //reset the key
			    boolean valid = key.reset();
			 
			    //exit loop if the key is not valid
			    //e.g. if the directory was deleted
			      if (!valid) {
			          break;
			      }
			  }
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public void requestStop() {
		  isStopped = true;
		}
	
	public void requestRestart() {
		  isStopped = false;
		}
	
    public void call(String info){
        if(countObservers()>0){
            setChanged();
            notifyObservers(info);
        }
    } 
}
